<template>
	<view class="content">
		<z-paging ref="pagingRef" :data-list="dataList" @query="queryList" :fixed="false">
			<!-- 列表项渲染 -->
			<template v-for="(item, index) in dataList" :key="item.id || index">
				<!-- 兼职项 -->
				<view class="item" @click="itemClick(item)" v-if="item.type === 'PART_TIME_JOB'">
					<view class="uni-flex">
						<text class="text1">{{ item.collectPartTimeResult.name }}</text>
						<!-- 平台推荐标识 -->
						<view class="uni-flex uni-align-center xing_box"
							v-if="item.collectPartTimeResult.isRecommended==='1'">
							<image :src="`${$ImgBaseUrl}part_time_xing.png`" mode="widthFix" class="xing_icon" />
							<text class="text2">平台推荐</text>
						</view>
					</view>
					<text v-for="(label, i) in item?.collectPartTimeResult?.labels" :key="i"
						class="project">
						{{ label }}
					</text>
					<view class="uni-flex uni-justify-between uni-align-center line3">
						<view class="price-container">
							<text class="money-symbol">¥</text>
							<text class="money">{{ item.collectPartTimeResult.price }}</text>
							<!-- <text class="money_tip">元/小时</text> -->
						</view>
						<!-- 兼职项收藏按钮 -->
						<image
							:src="item.collect ? `${$ImgBaseUrl}lookforsb-collect-selected.png` : `${$ImgBaseUrl}detail_collect.png`"
							class='colletc' mode="widthFix" @click.stop="handleCollect(item, index)" />
					</view>
				</view>
				<!-- 找活项 -->
				<view class="item" v-if="item.type === 'JOB'" @click="itemClick(item)">
					<view class="uni-flex uni-align-center top">
						<image :src="item.busJobResult.titleImage" class="photo" />
						<view class="uni-flex-column center">
							<text class="title">{{item.busJobResult.name===null?'--':item.busJobResult.name}}</text>
							<text
								class="distance">距您{{item.busJobResult.distance===null?'--':item.busJobResult.distance}}km</text>
						</view>
						<view class="uni-flex-column uni-align-center">
							<text
								:class="item.busJobResult.closeRate<=30?'num-red':item.busJobResult.closeRate<=60?'num-orange':'num'">{{item.busJobResult.closeRate}}%</text>
							<text class="text-findJob">结单率</text>
						</view>
					</view>
					<text v-for="(label, index) in item.busJobResult.labelNames" :key="index" class="project-findJob">
						{{ label }}
					</text>
					<view class="box-findJob">
						<text class="text-findJob">服务地址：</text>
						<text
							class="text2-findJob">{{item.busJobResult.address===null?'--':item.busJobResult.address}}</text>
					</view>
					<view class="uni-flex box-findJob">
						<view class="left-findJob">
							<view class="">
								<text class="text-findJob">发布时间：</text>
								<text
									class="text2-findJob">{{item.busJobResult.createTime===null?'--':item.busJobResult.createTime}}</text>
							</view>
							<!-- 找活项收藏按钮 -->
							<image
								:src="item.collect ? `${$ImgBaseUrl}lookforsb-collect-selected.png` : `${$ImgBaseUrl}detail_collect.png`"
								class='colletc' mode="widthFix" @click.stop="handleCollect(item, index)" />
						</view>
						<text class="text3" v-if="item.isBrowse">浏览过</text>
					</view>
				</view>
			</template>
			<!-- 空状态 -->
			<template #empty>
				<view class="empty-container">
					<text>暂无数据</text>
				</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		nextTick,
		reactive,
		toRefs,
		// 新增：引入Vue的set方法
		set
	} from "vue";
	import {
		userCollectApi
	} from "@/api/personalFavorites.js";
	import {
		onShow
	} from '@dcloudio/uni-app';
	import {
		PeopleDetailCollect
	} from '@/api/findPeople.js'

	// 接收父组件参数
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0
		},
		currentIndex: {
			type: Number,
			default: 0
		},

		browseType: {
			type: String,
			default: ''
		},

	});

	// 响应式数据
	const state = reactive({
		dataList: [],
		totalCount: 0,
		loading: false // 收藏操作加载状态
	});
	const {
		dataList,
		totalCount,
		loading
	} = toRefs(state);

	// z-paging组件引用
	const pagingRef = ref(null);
	const firstLoaded = ref(false); // 标记是否首次加载

	// 监听父组件currentIndex变化
	watch(
		() => props.currentIndex,
		(newVal) => {
			if (newVal === props.tabIndex) {
				if (!firstLoaded.value) {
					nextTick(() => {
						setTimeout(() => {
							firstLoaded.value = true;
							pagingRef.value?.reload();
						}, 100);
					});
				} else {
					// reload();
				}
			} else {
				firstLoaded.value = false;
			}
		}
	);


	// 列表数据请求
	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize: pageSize,
				browseType: props.browseType
			};
			const res = await userCollectApi(params);
			if (res && res.code === 200) {
				const result = res.rows || [];
				state.totalCount = res.total || 0;
				state.dataList = pageNum === 1 ? result : [...state.dataList, ...result];
				pagingRef.value.complete(result, pageNum * pageSize >= state.totalCount);
			} else {
				state.dataList = [];
				pagingRef.value.complete([], true);
			}
		} catch (error) {
			console.error('接口调用失败:', error);
			pagingRef.value.complete(false);
		}
	};

	// 刷新列表
	const reload = () => {
		nextTick(() => {
			state.dataList = [];
			state.totalCount = 0;
			// pagingRef.value?.reload();
		});
	};

	// 暴露刷新方法给父组件
	defineExpose({
		reload
	});

	// 列表项点击事件
	const itemClick = (item) => {
		console.log('点击项:', item);
		if (item.type === 'PART_TIME_JOB') {
			uni.navigateTo({
				url: `/pages/tabBars/findPartTimeJob/partTimeDetail?id=${item.collectPartTimeResult.id}`
			});
		} else if (item.type === 'JOB') {
			uni.navigateTo({
				url: `/pages/tabBars/findJob/jobDetail?jobId=${item.busJobResult.id}`
			});
		}
	};

	// 收藏/取消收藏处理
	const handleCollect = async (item, index) => {
		if (loading.value) return; // 防止重复点击

		try {
			state.loading = true;

			// 获取collectId
			let collectId;
			if (item.type === 'JOB') {
				collectId = item.busJobResult?.id || '';
			} else if (item.type === 'PART_TIME_JOB') {
				collectId = item.collectPartTimeResult?.id || '';
			} else {
				throw new Error('未知的项目类型，无法获取collectId');
			}

			// 接口参数
			const params = {
				collectId: collectId,
				collectType: item.type,
				isCollect: !item.collect
			};

			// 调用收藏接口
			const res = await PeopleDetailCollect(params);

			if (res.code === 200) {
				// 关键修正：判断原状态是否为“已收藏”（取消收藏操作）
				if (item.collect) {
					// 取消收藏：从列表中移除该项
					state.dataList.splice(index, 1);
					// 更新总条数（同步减少）
					state.totalCount--;
					uni.showToast({
						title: '取消收藏成功',
						icon: 'success',
						duration: 1500
					});
				} else {
					// 收藏操作：仅更新本地状态（不修改列表）
					item.collect = true;
					uni.showToast({
						title: '收藏成功',
						icon: 'success',
						duration: 1500
					});
				}

				// 通知分页组件刷新UI（同步列表变化）
				nextTick(() => {
					// pagingRef.value.refresh();
				});

			} else {
				// 操作失败
				uni.showToast({
					title: res?.msg || (item.collect ? '取消收藏失败' : '收藏失败'),
					icon: 'none',
					duration: 2000
				});
			}
		} catch (error) {
			console.error('收藏操作失败:', error);
			uni.showToast({
				title: error.message || '操作失败，请稍后重试',
				icon: 'none',
				duration: 2000
			});
		} finally {
			state.loading = false; // 结束加载状态
		}
	};
</script>

<style lang="scss" scoped>
	/* 原有样式保持不变 */
	.content {
		height: calc(100vh - 250rpx);
		background: #F5F5F5;
	}

	.item {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
		background-color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.uni-flex {
		display: flex;
	}

	.uni-align-center {
		align-items: center;
	}

	.text1 {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.xing_box {
		margin: 0 0 17rpx 19rpx;
	}

	.xing_icon {
		width: 47rpx;
		height: 47rpx;
	}

	.text2 {
		font-weight: 500;
		font-size: 24rpx;
		color: #fe9010;
		background: #fff5e0;
		border-radius: 0 21px 21px 0;
		padding: 5rpx 10rpx;
	}

	.project {
		display: inline-block;
		padding: 6rpx 16rpx;
		background: #F8F8F8;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: #666;
		margin-right: 12rpx;
		margin-top: 16rpx;
	}

	.line3 {
		margin-top: 30rpx;
	}

	.price-container {
		position: relative;
		display: inline-flex;
		align-items: flex-end;
	}

	.money-symbol {
		font-size: 24rpx;
		color: #FF5A1F;
		position: relative;
		bottom: 4rpx;
		right: 4rpx;
	}

	.money {
		font-size: 36rpx;
		color: #FF5A1F;
		font-weight: bold;
	}

	.money_tip {
		font-size: 24rpx;
		color: #999;
		margin-left: 8rpx;
		align-self: flex-end;
	}

	.colletc {
		width: 25rpx;
		height: 25rpx;
		display: block;
	}

	.empty-container {
		text-align: center;
		padding: 40rpx;
		font-size: 28rpx;
	}

	/* 找活项样式 */
	.item {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		margin: 26rpx 24rpx 0;

		.top {
			padding-bottom: 18rpx;
			border-bottom: 1rpx solid #ededed;
			margin-bottom: 18rpx;

			.photo {
				width: 88rpx;
				height: 88rpx;
				border-radius: 50%;
				margin-right: 24rpx;
			}

			.center {
				flex: 1;
			}

			.title {
				font-size: 28rpx;
				font-weight: 500;
				color: #333;
				margin-bottom: 12rpx;
			}

			.distance {
				font-size: 24rpx;
				color: #666;
			}

			.num-findJob {
				font-size: 36rpx;
				font-weight: 500;
				color: #FF6A47;
				margin-bottom: 10rpx;
			}

			.text-findJob {
				font-size: 22rpx;
				color: #999;
			}

			.num {
				font-size: 36rpx;
				font-weight: bold;
				color: #6bc98d;
				font-weight: 500;
				margin-bottom: 10rpx;
			}

			.num-red {
				font-weight: 500;
				font-size: 36rpx;
				color: #FF6A47;
			}

			.num-orange {
				font-weight: 500;
				font-size: 36rpx;
				color: #FEB310;
			}
		}

		.project-findJob {
			color: #2f80ed;
			font-size: 24rpx;
			font-weight: 500;
			background: #e6f1ff;
			padding: 6rpx 10rpx;
			margin-right: 14rpx;
			border-radius: 4rpx;
		}

		.box-findJob {
			font-size: 24rpx;
			margin-top: 16rpx;

			.left-findJob {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.text-findJob {
				color: #999;
			}

			.text2-findJob {
				color: #333;
			}

			.text3 {
				color: #999;
			}

			.left {
				flex: 1;
			}
		}
	}
</style>